package com.wHitE.servlet;

import com.google.gson.*;
import com.wHitE.pojo.Book;
import com.wHitE.pojo.BookList;
import com.wHitE.utils.Result;
import com.wHitE.service.BookListService;
import com.wHitE.service.impl.BookListServiceImpl;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/bookList")
public class BookListServlet extends HttpServlet {
    private BookListService bookListService = new BookListServiceImpl();

    @Override
    public void init(ServletConfig config) throws ServletException {
        System.out.println("查询书籍列表接口初始化...");
        super.init(config);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("查询书籍列表接口调用...");
        super.service(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 获取out对象
        PrintWriter out = resp.getWriter();

        String name = req.getParameter("name");
        String pageNum = req.getParameter("pageNum");
        String pageCount = req.getParameter("pageCount");

        // 初始化 object=>json 对象
        // 这里因为需要自定义处理日期格式,所以使用gson构造器设置日期格式如 2023-11-17
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();


        BookList res;

        if (name.equals("null") || name.equals("")) {
            res = bookListService.bookList(Integer.parseInt(pageNum), Integer.parseInt(pageCount));
        } else {
            res = bookListService.bookList(name, Integer.parseInt(pageNum), Integer.parseInt(pageCount));
        }
        // 判断是否请求成功...并响应给前端
        out.print(gson.toJson(Result.success(res)));
    }

    @Override
    public void destroy() {
        System.out.println("查询书籍列表接口关闭...");
    }
}
